package com.sihan.framework.etm.common.websocket;

import com.sihan.framework.etm.common.websocket.handler.MyWsHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.web.socket.config.annotation.*;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * WebSocket 配置类
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer implements WebSocketConfigurer {

    @Autowired
    private WebSocketInterceptor webSocketInterceptor;

    @Autowired
    private MyWsHandler myWsHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                .addHandler(myWsHandler, "/socket")
                //允许跨域
                .setAllowedOrigins("*")
                .addInterceptors(webSocketInterceptor);
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //添加一个stomp协议的endpoint
        registry.addEndpoint("/server").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //添加一个topic代理节点
        registry.enableSimpleBroker("/topic");
    }


    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        //添加路由拦截，判断请求头是否带上token、token是否有效
        registration.interceptors((ChannelInterceptor) webSocketInterceptor);
    }
}
